package com.taldh.jvm;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

public class ClassLoaderTest {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".")+1) + ".class";

                    InputStream is = getClass().getResourceAsStream(fileName);

                    if (is == null) {
                        return super.loadClass(name);
                    }

                    byte[] b = new byte[is.available()];

                    is.read(b);
                    return defineClass(name, b, 0 , b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException();
                }
            }
        };

        Object object = myLoader.loadClass("com.taldh.jvm.SubClass").getDeclaredConstructor().newInstance();
        System.out.println(object.getClass());
        System.out.println(object instanceof SubClass);

        System.out.println(Thread.currentThread().getContextClassLoader());
        System.out.println(object.getClass().getClassLoader());
        System.out.println(SubClass.class.getClassLoader());

        System.out.println(Object.class.getClassLoader());
    }

}



